package bd403.UIComponents;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.ListIterator;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import bd403.Backend.Drink;
import bd403.Backend.DrinkStorage;
import bd403.Backend.Review;
import bd403.namespace.BDActivity;
import bd403.namespace.R;
import bd403.utils.ReviewAdapter;

/* UI and functionality for an individual drink page.
 * Main author: Joseph
 */

public class DrinkViewActiv extends ListActivity {

    private ReviewAdapter rAdapter;
    private ArrayList<Review> reviews;
    private Drink currentDrink;

    /* Initializes the the UI for the page.
	 */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drink);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Get the current Drink that's being viewed
        DrinkStorage ds = BDActivity.getStorage();
        currentDrink = ds.getCurrentDrink();
        
        // Initialize list of reviews
        getReviews();
        
        this.rAdapter = new ReviewAdapter(this, R.layout.reviewitem, reviews);
        setListAdapter(this.rAdapter);
        
        setDrinkText(currentDrink);
        setViewSettings();
        setupAddReviewListener();
        setupAddFavoritesListener();
    }
    
    /* Sets up the options menu for the DrinkViewActiv.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(getString(R.string.title_help));
		return true;
    }
	
	/* Launches the Help page once it is clicked from the options menu.
	 */
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		Intent i = new Intent(this, HelpActiv.class);
        startActivity(i);
        return true;
    }

    /* Set the list view to the proper color and make the list non-clickable.
     */
    private void setViewSettings() {
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);    //Allows user to filter list by typing on the keyboard
        // So the comments aren't clickable
        lv.setSelector(android.R.color.transparent);
    }

    /* Sets the info for the current drink the user is viewing
     */
    private void setDrinkText(Drink d) {
        TextView drinkTitle = (TextView) findViewById(R.id.view_drinktitle);
        TextView drinkRating = (TextView) findViewById(R.id.view_drinkrating);
        ImageView iv = (ImageView) findViewById(R.id.icon);


        drinkTitle.setText(d.getName());
        
        // To handle the edge case properly
        int total = currentDrink.getNumRatings();
        String ratings = getString(R.string.drinklabel_ratings);
        if (total == 1) {
        	ratings = getString(R.string.drinklabel_rating);
        }
        DecimalFormat f = new DecimalFormat(getString(R.string.numberformat_rating));
        drinkRating.setText(getString(R.string.drinklabel_avgrating) + f.format(d.getRating()) + 
        		"\t\t\t" + total + ratings);
        
        if (iv != null) {
            switch(d.getType()) {
            case 0 : 
                iv.setImageResource(R.drawable.beer_icon);
                break;
            case 1 :
                iv.setImageResource(R.drawable.wine);
                break;
            case 2 :
                iv.setImageResource(R.drawable.cocktail);
                break;
            default :
                iv.setImageResource(R.drawable.default_icon);
            }
        }
    }

    /* Sets up the list of this drink's Reviews
     */
    private void getReviews() {
        reviews = new ArrayList<Review>();
        ListIterator<Review> it = currentDrink.getReviews();
        while (it.hasPrevious()) {
            Review r = it.previous();
            if (r.hasComment()) {
                reviews.add(r);
            }
        }
    }

    /* Sets up what happens when user clicks "Add Review"
     */
    private void setupAddReviewListener() {
        /* Set up the listener for switching to AddReviewActiv */
        Button addReview = (Button) findViewById(R.id.submitReviewRequest);
        addReview.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	String drinkName = currentDrink.getName();
            	DrinkStorage ds = BDActivity.getStorage();

            	// Ensure that this user hasn't already reviewed this Drink.
            	if (ds.userReviewExists(drinkName)) {
            		Toast.makeText(getApplicationContext(), getString(R.string.toast_review_already), Toast.LENGTH_SHORT).show();
            	} else {
            		startActivity(new Intent(getApplicationContext(), AddReviewActiv.class));
            		finish();
            	}
            } 
        });
    }
    
    /* Setup the listener for adding this Drink to the current User's list of
     * favorite Drinks
     */
    private void setupAddFavoritesListener() {
    	Button addFavorite = (Button) findViewById(R.id.addToFavorites);
    	addFavorite.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
				try {
					if (BDActivity.getStorage().addUserFavorite(currentDrink)) {
						Toast.makeText(getApplicationContext(), 
								getString(R.string.toast_addfav_success_pre) + currentDrink.getName() + 
								getString(R.string.toast_addfav_success_post), Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(), getString(R.string.toast_addfav_error), Toast.LENGTH_SHORT).show();
					}
				} catch (IllegalStateException e) {
					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		});
    }
}
